package lhy.autoparts.servlet;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lhy.autoparts.SharedConstant;
import lhy.autoparts.table.EntityTableService;
import lhy.orm.model.EntityData;
import lhy.orm.model.FieldData;
import lhy.utils.DateUtils;
import lhy.utils.IdUtils;
import lhy.utils.ReflectUtils;

import java.util.Arrays;

@WebServlet("/CrudPreprocessServlet")
public class CrudPreprocessServlet extends Utf8Servlet{
    @Override
    protected void doGet(HttpServletRequest que, HttpServletResponse pon) {
        super.doGet(que, pon);
        String entityClassName = que.getParameter("entityClassName");
        Class<?> entityClass = ReflectUtils.loadClassByName(entityClassName);
        que.setAttribute("entityClassName",entityClassName);

        EntityData entityData = EntityTableService.getEntityData(entityClassName);
        que.setAttribute("entityData",entityData);

        que.setAttribute("tableContentRequestUrl",que.getContextPath());

        //如果传进来的实体类需要自动生成单号，就自动生成单号
        if(SharedConstant.AUTO_GENERATE_ID_ENTITY_PREFIX.keySet().contains(entityClass)){
            String prefix = SharedConstant.AUTO_GENERATE_ID_ENTITY_PREFIX.get(entityClass);
            String generatedOrderId = IdUtils.generateIdWithDate();
            que.setAttribute("generatedOrderId",prefix+generatedOrderId);
        }
        //如果有日期
        if(Arrays.stream(entityData.getFields()).anyMatch(FieldData::isDate)){
            que.setAttribute("dateToday", DateUtils.getDateNow());
        }

        String condition = que.getParameter("condition");
        if(condition!=null){
            que.setAttribute("condition",condition);
            que.setAttribute("conditionName",condition.split("=")[0]);
            que.setAttribute("conditionValue",condition.split("=")[1]);
        }
        forwardRequest("crud_table.jsp",que,pon);
    }
}
